<?php


namespace app\article\controller;


use app\AdminRest;
use app\article\model\ArticleClassifyModel;
use app\article\model\ArticleContentModel;
use app\article\model\ArticleModel;
use think\App;
use think\facade\Db;

class AdminArticle extends AdminRest
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function listAll()
    {
        $param = $this->_param;
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        $filter = [
            ['uniacid', '=', $this->_uniacid],
            ['user_id', '=', 0],
            ['status', '<>', -1]
        ];
        if (isset($param['keyWordForTitle'])) {
            array_push($filter, ['title', 'like', '%' . $param['keyWordForTitle'] . '%']);
        }
        if (isset($param['classify_id']) && $param['classify_id'] > 0) {
            array_push($filter, ['classify_id', '=', $param['classify_id']]);
        }
        $model = new ArticleModel();
        $page_config['total'] = $model->countByFilter($filter);
        $rsts = $model->getListByFilter($filter, $page_config);

        $content_ids = array_column($rsts, 'content');

        if ($content_ids)
        {
            $contents = [];
            $content_temp = Db::name('lb_marketing_article_content')->where('id', 'in', $content_ids)->select()->toArray();
            foreach ($content_temp as $item) {
                $contents[$item['id']] = $item['content'];
            }

            foreach ($rsts as $k => $v) {
                $rsts[$k]['content_id'] = $v['content'];
                $rsts[$k]['content'] = $contents[$v['content']] ?? '';
            }
        }

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $result['data'] = $rsts;

        if ($result['data'])
        {
            $classifyModel = new ArticleClassifyModel();

            $classify = $classifyModel
                ->field('id, title')
                ->where(['uniacid' => $this->_uniacid])
                ->select()->toArray();

            foreach ($result['data'] as $index => $item) {
                foreach ($classify as $k => $v) {
                    if ($item['classify_id'] == $v['id'])
                    {
                        $result['data'][$index]['classify_title'] = $v['title'];
                    }
                }
            }
        }


        return $this->success($result);
    }

    public function listStaffArticle()
    {
        $param = $this->_param;
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        $filter = [
            ['uniacid', '=', $this->_uniacid],
            ['user_id', '<>', 0],
            ['status', '<>', -1]
        ];
        if (isset($param['keyWordForTitle']))
        {
            array_push($filter, ['title', 'like', '%' . $param['keyWordForTitle'] . '%']);
        }
        if (isset($param['classify_id']) && $param['classify_id'] > 0)
        {
            array_push($filter, ['classify_id', '=', $param['classify_id']]);
        }
        $model = new ArticleModel();
        $page_config['total'] = $model->countByFilter($filter);
        $rsts = $model->getListByFilter($filter, $page_config);

        $user_ids = array_column($rsts, 'user_id');

        if ($user_ids)
        {
            $users = [];
            $users_temp = Db::name('longbing_card_user')->alias('a')
                ->field(['b.name', 'a.id'])
                ->where('a.id', 'in', $user_ids)
                ->join('longbing_card_user_info b', 'b.fans_id = a.id')->select()->toArray();

            foreach ($users_temp as $item) {
                $users[$item['id']] = $item['name'];
            }

            foreach ($rsts as $k => $v) {
                if(key_exists($v['user_id'],$users)){
                    $rsts[$k]['staff_name'] = $users[$v['user_id']];
                }
            }
        }


        $content_ids = array_column($rsts, 'content');

        if ($content_ids)
        {
            $contents = [];
            $content_temp = Db::name('lb_marketing_article_content')->where('id', 'in', $content_ids)->select()->toArray();
            foreach ($content_temp as $item) {
                $contents[$item['id']] = $item['content'];
            }

            foreach ($rsts as $k => $v) {
                $rsts[$k]['content_id'] = $v['content'];
                $rsts[$k]['content'] = $contents[$v['content']] ?? '';
            }
        }

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $result['data'] = $rsts;

        if ($result['data'])
        {
            $classifyModel = new ArticleClassifyModel();

            $classify = $classifyModel
                ->field('id, title')
                ->where(['uniacid' => $this->_uniacid])
                ->select()->toArray();

            foreach ($result['data'] as $index => $item) {
                foreach ($classify as $k => $v) {
                    if ($item['classify_id'] == $v['id'])
                    {
                        $result['data'][$index]['classify_title'] = $v['title'];
                    }
                }
            }
        }

        return $this->success($result);
    }

    public function createOne()
    {
        $input = $this->_input;
        $title = $input['title'] ?? null;
        if (!$title)
        {
            return $this->error('title is required');
        }

        $classify_id = $input['classify_id'] ?? null;
        if (!$classify_id)
        {
            return $this->error('classify_id is required');
        }


        if (empty($input['cover']))
        {
            return $this->error('cover is required');
        }

//        if (empty($input['top']))
//        {
//            return $this->error('top is required');
//        }


        if (empty($input['content']))
        {
            return $this->error('content is required');
        }


        if ($input['content'])
        {
            $contentModel = new ArticleContentModel();
            $contentModel->cover = $input['cover'] ?? "";
            $contentModel->content = $input['content'];
            $contentModel->status = 1;
            $contentModel->uniacid = $this->_uniacid;
            $contentModel->save();
            $content_id = $contentModel->id;
        }

        $input['content'] = $content_id ?? 0;

        $input['uniacid'] = $this->_uniacid;
        $model = new ArticleModel();
        $input['user_id'] = 0;
        $id = $model->createOne($input);

        return $this->success($id);
    }

    public function updateOne()
    {
        $id = $this->_param['id'] ?? null;
        if (!$id) {
            return $this->error('article_id is required');
        }
        $input = $this->_input;

        $model = new ArticleModel();

        $old_info = $model->find(['id' => $id])->toArray();
        if (!$old_info)
        {
            return $this->error('this article not found');
        }
        $content = $input['content'] ?? null;
        unset($input['content']);
        $data = $model->updateByfilter(['id' => $id], $input);

        $contentModel = new ArticleContentModel();

        $update = [];
        if ($content !== null)
        {
            $update['content'] = $content;
        }

        if (!empty($input['cover']))
        {
            $update['cover'] = $input['cover'];
        }
        if (!empty($update))
        {
           $rst =  $contentModel->where(['id' => $old_info['content']])->update($update);
           if (!$rst) {
               $update['uniacid'] = $this->_uniacid;
               $update['url'] = '';
               $content_id = $contentModel->insert($update, true);

               $content_id &&  $model->updateByfilter(['id' => $id], ['content' => $content_id]);
           }
        }

        return $this->success($data);
    }

    public function getOne()
    {
        $id = $this->_param['id'];
        if (!$id)
        {
            return $this->error('article_id is required');
        }
        $model = new ArticleModel();
        $data = $model->getOne(['id' => $id]);
        if ($data)
        {
            $contentModel = new ArticleContentModel();
            $content = $contentModel->find(['id' => $data['content']]);
            $data['content'] = $content ? htmlspecialchars_decode($content['content']) : '';
        }
        return $this->success($data);
    }

    public function changeStatus()
    {
        $id = $this->_param['id'];
        if (!$id)
        {
            return $this->error('fail');
        }
        $input = $this->_input;
        $model = new ArticleModel();

        $rst = $model->updateByfilter(['id' => $id], ['status' => $input['status']]);
        return $this->success($rst);
    }


    public function syncStaffArticle()
    {
        $id = $this->_param['id'] ?? null;
        if (!$id)
        {
            return $this->error('fail');
        }
        $model = new ArticleModel();
        $article_staff = $model->where([
            ['id', '=', $id],
            ['user_id', '>', 0],
        ])->find();

        if (!$article_staff)
        {
            return $this->error('fail');
        }

        $article_admin = $model->where(['source_id' => $id, 'user_id' => 0])->find();

        if ($article_admin)
        {
            $article_admin->classify_id = $article_staff->classify_id;
            $article_admin->title = $article_staff->title;
            $article_admin->cover = $article_staff->cover;
            $article_admin->content = $article_staff->content;
            $article_admin->status = 1;
            $article_admin->update_time = time();
        } else
            {
            $article_admin = new ArticleModel();
            $article_admin->classify_id = $article_staff->classify_id;
            $article_admin->source_id = $article_staff->id;
            $article_admin->title = $article_staff->title;
            $article_admin->cover = $article_staff->cover;
            $article_admin->content = $article_staff->content;
            $article_admin->view = 0;
            $article_admin->share = 0;
            $article_admin->thumb = 0;
            $article_admin->uniacid = $article_staff->uniacid;
            $article_admin->status = 1;
            $article_admin->create_time = time();
            $article_admin->update_time = time();
            $article_admin->user_id = 0;
        }

        $rst = $article_admin->save();

        return $this->success($rst);

    }

}